<template>
  <div v-if="dataList" class="content-wrapper">
    <div class="content-header">
      <span v-if="dataList[0].flowType == 1">新增流程</span>
      <span v-if="dataList[0].flowType == 2">修订流程</span>
      <span v-if="dataList[0].flowType == 3">作废流程</span>
      <span v-if="dataList[0].flowType == 4">下载流程</span>
      <span>({{ phaseName }})</span>
    </div>

    <div class="content-container">
      <div class="filter-container" />
      <div class="block-box">
        <div class="block-left">
          <div class="block">
            <el-card class="box-card" shadow="hover">
              <div slot="header" class="clearfix">
                <span>基本信息</span>
              </div>
              <el-form>
                <el-table
                  ref="table"
                  :data="temp"
                  style="width: 100%"
                  :highlight-current-row="true"
                  max-height="500"
                >
                  <el-table-column
                    :key="Math.random()"
                    prop="documentName"
                    label="文件名称"
                    min-width="200"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :key="Math.random()"
                    width="160"
                    prop="content"
                    label="文件等级"
                  >
                    <template scope="{row}">
                      {{ formatByKeyValue(levels, row.documentLevel) }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    :key="Math.random()"
                    width="160"
                    prop="content"
                    label="文件属性"
                  >
                    <template scope="{row}">
                      {{
                        formatByKeyValueTo(
                          levels,
                          row.documentProperty,
                          row.documentLevel
                        )
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    :key="Math.random()"
                    prop="documentCode"
                    label="文件编号"
                    min-width="220"
                  />

                  <el-table-column
                    :key="Math.random()"
                    prop="documentVersion"
                    label="版本号"
                    width="150"
                  />
                  <el-table-column
                    :key="Math.random()"
                    prop="urgent"
                    label="紧急程度"
                    width="150"
                  >
                    <template scope="{row}">
                      <span v-if="row.urgent == 0"> 正常 </span>
                      <span v-else>紧急</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    :key="Math.random()"
                    fixed="right"
                    label="操作"
                    width="200px"
                  >
                    <template slot-scope="scope">
                      <!-- 编辑 -->
                      <el-tooltip
                        v-if="isEdit"
                        effect="dark"
                        content="编辑文件"
                        placement="top"
                      >
                        <el-button
                          size="mini"
                          circle
                          @click.native="openDocument('edit', scope.row)"
                          ><i class="el-icon-edit" />
                        </el-button>
                      </el-tooltip>

                      <!-- 查看 -->
                      <el-tooltip
                        v-if="isView"
                        effect="dark"
                        content="查看文件"
                        placement="top"
                      >
                        <el-button
                          size="mini"
                          circle
                          @click.native="openDocument('view', scope.row)"
                          ><i class="el-icon-view" />
                        </el-button>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>
            </el-card>
            <el-card class="box-card" shadow="hover">
              <div slot="header" class="clearfix">
                <span>流程信息</span>
              </div>
              <el-table
                :data="dataList"
                :show-header="false"
                style="width: 100%"
              >
                <el-table-column width="100px">
                  <template slot-scope="{ row }">
                    <el-tag v-if="row.result === 1" type="success">{{
                      row.phaseName
                    }}</el-tag>
                    <el-tag v-if="row.result === 2" type="danger">{{
                      row.phaseName
                    }}</el-tag>
                    <el-tag v-if="row.result === 3" type="warning">{{
                      row.phaseName
                    }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="handleUserName" width="150px" />
                <el-table-column prop="opinion" />
                <el-table-column prop="createTime" width="160px" />
              </el-table>
            </el-card>
            <el-card
              v-if="dataList[dataList.length - 1].phase == 'release'"
              class="box-card"
              shadow="hover"
            >
              <template>
                <div slot="header" class="clearfix">
                  <span>签收情况</span>
                </div>
                <el-table
                  ref="table"
                  :data="temp"
                  style="width: 100%"
                  row-key="documentId"
                >
                  <el-table-column width="50">
                    <template slot-scope="scope">
                      <i
                        class="el-icon-arrow-down"
                        @click="getRowSignCondition(scope.row, scope.$index)"
                      ></i>
                    </template>
                  </el-table-column>
                  <el-table-column type="expand" width="1">
                    <template scope="{row}">
                      <el-table :data="row.tableData" :row-key="keys">
                        <el-table-column prop="label" label="签收人" />
                        <el-table-column prop="groupName" label="所属部门" />
                        <el-table-column prop="signForStatus" label="签收情况">
                          <template slot-scope="{ row }">
                            <el-tag
                              v-if="row.signForStatus == 0"
                              size="mini"
                              type="danger"
                              >未签收</el-tag
                            >
                            <el-tag
                              v-if="row.signForStatus == 1"
                              size="mini"
                              type="success"
                              >已签收</el-tag
                            >
                          </template>
                        </el-table-column>
                      </el-table>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="documentName"
                    label="文件名称"
                  ></el-table-column>
                  <el-table-column
                    prop="documentCode"
                    label="文件编号"
                  ></el-table-column>
                </el-table>
              </template>
            </el-card>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { get, set } from '@/utils/db'
import {
  nodesHandle,
  getPhase,
  getFlow,
  getPhaseSmall,
  releaseCheck,
  inquireDocumentFlow,
  assigneeDocumentFlow,
  getDocumentFlow
} from '@/api/xd/documentFlow'
import { listDictTreeItem } from '@/api/base/dict'
import { expandArrUser } from '@/utils/common.js'

export default {
  data() {
    return {
      dataList: [{ flowType: '' }],
      id: '',
      tableData: [],
      i: 0,
      temp: [],
      levels: [],
      categories: [],
      isEdit: true,
      isView: true,
      assigneeUserList: [],
      phaseName: null,
      INDEX: 0
    }
  },
  watch: {
    dataList(data) {
      // this.signCondition()
    }
  },
  mounted() {
    this.data()
  },
  updated() {},
  methods: {
    formatByKeyValue(options, key) {
      options = options || []
      let label = ''
      options.forEach((e) => {
        if (e.value === key + '') {
          label = e.label
        }
      })
      return label
    },

    formatByKeyValueTo(options, key, level) {
      let label = ''
      for (let i = 0, len = options.length; i < len; i++) {
        if (options[i].value === level + '') {
          label = this.formatByKeyValue(options[i].children, key)
        }
      }
      return label
    },
    loadLevelOptions() {
      listDictTreeItem({ dictGroupCode: 'document_category' }).then((res) => {
        this.levels = res.data
        // if (array) {
        //   for (let i = 0, len = array.length; i < len; i++) {
        //     if (array[i].value === '1') {
        //       array.splice(i, 1)
        //       break
        //     }
        //   }
        // }
      })
    },
    async data() {
      const row = JSON.parse(this.$route.query.row)
      this.id = row.documentFlowId
      this.phaseName = row.phaseName
      if (!this.id) {
        this.id = JSON.parse(get('PreviewId'))
      }
      const data = await nodesHandle({
        documentFlowId: this.id
      })
      this.dataList = data.data || []
      this.isRelease(this.dataList)
      set('PreviewId', JSON.stringify(this.id))
      this.assigneeUserList = await assigneeDocumentFlow({
        documentFlowId: this.id
      })
      await this.isAssignee(this.dataList)
      if (row.batchType === 1) {
        inquireDocumentFlow({
          batchType: 2,
          parentDocumentFlowId: this.id,
          pageSize: 100
        }).then((res) => {
          this.temp = res.data
        })
      } else {
        getDocumentFlow({
          documentFlowId: this.id
        }).then((res) => {
          this.temp = [res.data]
        })
      }

      this.loadLevelOptions()
    },
    isRelease(data) {
      data.forEach((e) => {
        if (e.phase === 'approve') {
          this.isEdit = false
        }
      })
      if (data.length < 3) {
        this.isEdit = false
        this.isView = false
      }
    },
    isAssignee(data) {
      let isDraft = false
      let isReview = false
      let reviewIndex = null
      const reviewList = []
      for (let i = 0; i < data.length; i++) {
        if (data[i].phase === 'review') {
          reviewIndex = i
          isReview = true
          reviewList.push(data[i])
        }
        if (data[i].phase === 'draft') {
          isDraft = true
        }
      }
      if (isDraft && !isReview) {
        const list = []
        this.assigneeUserList.data.forEach((item) => {
          list.push({
            phaseName: '文件评审',
            handleUserName: item.userName,
            userId: item.userId,
            result: 3,
            opinion: ''
          })
        })
        this.dataList = [...this.dataList, ...list]
      } else if (isReview) {
        const list = []
        this.assigneeUserList.data.forEach((item) => {
          reviewList.forEach((e, index) => {
            if (e.handleUserId !== item.userId) {
              list.push({
                phaseName: '文件评审',
                handleUserName: item.userName,
                userId: item.userId,
                result: 3,
                opinion: ''
              })
            } else {
              reviewList.splice(index, 1)
            }
          })
        })
        this.dataList = [...this.dataList, ...list]
      }
    },

    dispose() {
      const row = this.$route.query.row
      if (row.flowType == 1 || row.flowType == 2) {
        this.$router.push({
          path: getFlow(row.flowType) + row.documentFlowId,
          query: {
            phase: getPhase(row.phase)
          }
        })
      } else {
        this.$router.push({
          path: getFlow(row.flowType) + row.documentFlowId,
          query: {
            phase: getPhaseSmall(row.phase)
          }
        })
      }
    },
    getRowSignCondition(row, index) {
      this.$refs.table.toggleRowExpansion(row)
      this.signCondition(row, index)
      this.INDEX = index
    },
    async signCondition(row, index) {
      // if (this.dataList[this.dataList.length - 1].phase == 'release') {
      const { data } = await releaseCheck({
        documentFlowId: row.documentFlowId
      })
      const tableDataList = [...data.groupResponses, ...data.userResponses]
      tableDataList.forEach((item, index) => {
        if (item.userResponses == null && item.signForStatus == null) {
          delete item.userResponses
        }
      })
      this.keysList(tableDataList)
      const newTemp = new Object(this.temp)
      newTemp[this.INDEX].tableData = expandArrUser(tableDataList)
      this.temp = JSON.parse(JSON.stringify(newTemp))
    },
    keys(row) {
      // console.log(index)
      return row.keys
    },
    // 遍历keys
    keysList(data) {
      data.forEach((item, index) => {
        this.i++
        item.keys = this.i
        if (item.userResponses) {
          this.keysList(item.userResponses)
        }
      })
    },
    // 打开文档
    openDocument(val, row) {
      if (row.fileExtension.indexOf('.pdf') !== -1) {
        window.open(
          process.env.VUE_APP_BASE_API +
            '/api/fd/pdf/get_document_by_pdf?documentId=' +
            row.documentId
        )
      } else {
        window.open(
          'onlyoffice/createDocument.html?&token=' +
            this.$store.getters.token +
            '&documentId=' +
            row.documentId +
            '&mode=' +
            val +
            '&urldata=' +
            process.env.VUE_APP_BASE_API
        )
      }
    }
  }
}
</script>

<style lang="scss" scope >
.el-table__expand-column .cell {
  display: none;
}
.block-left {
  height: 80vh;
  overflow-y: auto;
  .el-timeline-me {
    width: 60vw;
    .el-card__body {
      padding: 20px;
    }
  }
}
.block-right {
  padding-left: 50px;
}
.el-table {
  height: auto;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 96%;
  margin: 0 0 20px 0;
}
</style>
